import sys
import ctypes

class clipboard:
	@property
	def text(self):
		'''
		Get clipboard text if available
		'''
		# declare win32 API 
		user32		= ctypes.windll.user32
		kernel32	= ctypes.windll.kernel32

		if not user32.OpenClipboard(0):
			return ''

		CF_TEXT		= 1
		hClipMem	= user32.GetClipboardData(CF_TEXT)
		kernel32.GlobalLock.restype	= ctypes.c_char_p
		value		= kernel32.GlobalLock(hClipMem)
		kernel32.GlobalUnlock(hClipMem)
		user32.CloseClipboard()

		if isinstance(value, str):
			return value
		elif hasattr(value, 'decode'):
			return value.decode(sys.getfilesystemencoding())	
		else:
			return ''

	@text.setter
	def text(self, value):
		'''
		Set clipbard text
		'''
		if not isinstance(value, str):
			raise TypeError('value should be of str type')

		# declare win32 API
		user32		= ctypes.windll.user32
		kernel32	= ctypes.windll.kernel32

		GlobalLock	= kernel32.GlobalLock
		memcpy		= ctypes.cdll.msvcrt.memcpy

		CF_TEXT		= 1
		GHND		= 66

		buffer		= ctypes.c_buffer(value.encode(sys.getfilesystemencoding()))
		bufferSize	= ctypes.sizeof(buffer)
		hGlobalMem	= kernel32.GlobalAlloc(GHND, bufferSize)
		GlobalLock.restype	= ctypes.c_void_p
		lpGlobalMem	= GlobalLock(hGlobalMem)
		memcpy(lpGlobalMem, ctypes.addressof(buffer), bufferSize)
		kernel32.GlobalUnlock(hGlobalMem)
		if user32.OpenClipboard(0):
			user32.EmptyClipboard()
			user32.SetClipboardData(CF_TEXT, hGlobalMem)
			user32.CloseClipboard()
			return True

